import Mn from 'backbone.marionette';
import Radio from 'backbone.radio';
import { getOpt } from "../tools.js";


/** Combined input[type=file] and drag'n'drop zone
 *
 * intended for immediate upload (not part of a larger form)
 *
 * Requirements:
 * - `uploadAttachment(file)` radio request responding on `facade` channel
 */
const DropZoneWidget = Mn.View.extend({
    tagName: 'div',
    template: require('./templates/DropZoneWidget.mustache'),
    ui: {
        input: 'input[type=file]',
        dropzone: '.drop_files_here',
        form: 'form',
    },
    events: {
        // Mark zone as drag'n'drop target for browser
        'dragover @ui.dropzone': e => e.preventDefault(),
        'dragenter @ui.dropzone': e => e.preventDefault(),

        'drop @ui.dropzone': 'onFilesDropped',
        'change @ui.input': 'onFilesSelected',
    },
    onFilesDropped(event) {
        event.preventDefault();
        this.onFilesAdded(event.originalEvent.dataTransfer.files);
    },
    onFilesSelected(event) {
        this.onFilesAdded(event.target.files);
    },
    onFilesAdded(files) {
        let facade = Radio.channel('facade')
        for (let file of files) {
            facade.request('uploadAttachment', file);
        }
    }
});


export default DropZoneWidget;
